<!--
 * @Date: 2022-06-07 10:39:26
 * @Author: 陶子
 * @LastEditTime: 2023-07-04 10:56:24
 * @FilePath: \jk_one-stop_pc\src\components\pubBtn\PubImport.vue
 * @pageName: 这是--(公共导入组件)--页面
-->
<template>
  <div>
    <a-button @click='showImportModal' style='float: right' icon='download'>导入</a-button>
    <a-modal
      :maskClosable='false'
      :importModalTitle='importModalTitle'
      :visible='visible'
      :footer='null'
      title='导入'
      @cancel='handleCancel'
    >
      <a-alert class='alert' message='导入文件时，请按导入模板导入，若无模板请先下载导入模板' banner />
      <div class='import-salary'>
        <img src='@/assets/wenjian.png' alt='' class='icon' />
        <p>下载模板</p>
        <a-button type='primary' @click='downloadTemplate' style='margin-top: 5px'> 点击下载模板</a-button>
        <img src='@/assets/chooseFile.png' alt='' class='icon' style='top: 89px' />
        <p style='margin-top: 28px'>选择文件</p>

        <a-upload-dragger
          :remove='handleRemove'
          action='//jsonplaceholder.typicode.com/posts/'
          :file-list='fileList'
          :before-upload='beforeUpload'
          name='file'
          @change='handleChange'
        >
          <p class='ant-upload-drag-icon'>
            <img src='@/assets/tuozhuai.png' alt='' class='drag-icon' style='top: 89px' />
            <!-- <a-icon type="folder-open" /> -->
          </p>
          <p>将文件拖到此处，或者<span style='color: #1890ff'>点击选择</span></p>
        </a-upload-dragger>
        <p style='padding: 10px 0; color: #ff4d4f'>温馨提示：文件不能超过5M!</p>
      </div>
    </a-modal>
    <!--导入任务-->
    <div
      class='fixedBox'
      :style="{ height: isOpen ? '' : '56px', overflow: isOpen ? '' : 'hidden' }"
      v-show='importList.length > 0'
    >
      <div class='headerBox'>
        <div class='headerLeft'>导入任务（{{ importList.length }}）</div>
        <img class='headerRight' @click="changOpen('upwards')" src='@/assets/upwards.png' alt='' v-if='isOpen' />
        <img class='headerRight' @click="changOpen('downward')" src='@/assets/downward.png' alt='' v-else />
      </div>
      <div class='containerBox'>
        <div class='itemBox' v-for='item in importList' :key='item.id'>
          <div class='itemOne'>
            <div class='itemTop'>
              <div class='itemTop_left'>
                <img class='leftImg_ing' src='@/assets/importing.gif' alt='' v-if="item.status == 'uploading'" />
                <img class='leftImg_success' src='@/assets/success.png' alt='' v-if="item.status == 'upload_success'" />
                <img class='leftImg_fail' src='@/assets/fail.png' alt='' v-if="item.status == 'upload_error'" />
                <div class='leftText_ing' v-if="item.status == 'uploading'">导入中...</div>
                <div class='leftText_success' v-if="item.status == 'upload_success'">导入成功！</div>
                <div class='leftText_fail' v-if="item.status == 'upload_error'">导入失败！数据填写异常</div>
              </div>
              <div
                class='itemTop_right'
                @click='signRead(item)'
                v-if="item.status == 'upload_success' || item.status == 'upload_error'"
              >
                标记为已读
              </div>
            </div>
            <div class='btnBox' v-if="item.status == 'upload_error'">
              <a-button @click='downAbnormal(item)' icon='download' style='width: 105px'>下载异常表格</a-button>
            </div>
            <div class='itemCenter'>
              <span class='centerLeft'>导入时间：</span><span class='centerRight'>{{ item.createTime }}</span>
            </div>
            <div class='itemBot'>
              <span class='botLeft'>导入文件：</span><span class='botRight'>{{ item.initFileName }}</span>
            </div>
          </div>
          <div class='itemTwo'></div>
        </div>
      </div>
      <div class='footerBox'>
        <a-pagination
          :total='total'
          size='small'
          v-model='current'
          :page-size-options='pageSizeOptions'
          :page-size='pageSize'
          @change='onChangePage'
          @showSizeChange='onShowSizeChange'
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
  </div>
</template>
<script>
import { getAction, downFile, httpAction, fromDataPostAction, fromDataPost } from '@/api/manage'
import { sysUploadTaskList, deleteImport } from '@/api/productOrder'
import { apiBaseUrlDownload } from '@/utils/request'
import Vue from 'vue'
import { CURRENT_PREFIX } from '@/store/mutation-types'
import store from '@/store'

export default {
  //importModalTitle：导入弹框名，非必传；
  //modelName：模板文件名，必传
  //formType：下载模板、导入Excel文件接口参数,，必传；
  props: {
    importModalTitle: {
      type: String,
      default: '导入'
    },
    modelName: {
      type: String,
      required: true
    },
    formType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      fileList: [],
      fileLists: [],
      visible: false,
      /*导入任务列表变量*/
      current: 1,
      total: 0,
      pageSize: 30,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      isOpen: true,
      importList: [],
      setVal: null
    }
  },
  beforeDestroy() {
    clearInterval(this.setVal)
  },
  created() {
    let listObj = {
      pageNo: this.current,
      pageSize: this.pageSize
    }
    this.getData(listObj, true)
    this.setVal = setInterval(() => {
      this.current = 1
      this.pageSize = 30
      let obj = {
        pageNo: this.current,
        pageSize: this.pageSize
      }
      this.getData(obj, false)
    }, 5000)
  },
  methods: {
    getData(obj, flag) {
      let newObj = {
        ...obj,
        formType: this.formType
      }
      if (this.formType == 12 && !flag) {
        this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-produce/produce')
      }
      sysUploadTaskList(newObj).then((res) => {
        if (res.code == 200) {
          this.total = res.result.total
          this.importList = res.result.records
        } else {
          this.$antdMessage.error(res.message)
        }
      }).finally(() => {
        if (this.formType == 12 && !flag) {
          this.$store.commit('SET_CURRENT_PREFIX', '')
        }
      })
    },
    signRead(item) {
      let deleteObj = {
        id: item.id
      }
      if (this.formType == 12) {
        this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-produce/produce')
      }
      deleteImport(deleteObj).then((res) => {
        if (res.code == 200) {
          this.$antdMessage.success(res.message)
          this.current = 1
          this.pageSize = 30
          let obj = {
            pageNo: this.current,
            pageSize: this.pageSize
          }
          this.getData(obj)
        } else {
          this.$antdMessage.erro

          r(res.message)
        }
      }).finally(() => {
        if (this.formType == 12) {
          this.$store.commit('SET_CURRENT_PREFIX', '')
        }
      })
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      const type = file.name.split('.')[1]
      const size = file.size / 1024 / 1024
      console.log(type, size, 'type')
      if (size < 5) {
        if (type == 'xlsx' || type == 'xls') {
          this.fileLists = [...this.fileList, file]
          return false
        } else {
          this.$antdMessage.error('上传格式不正确')
          return true
        }
      } else {
        this.$antdMessage.error('上传文件大于5M，请重新上传')
        return true
      }
    },
    //导入模板下载
    downloadTemplate() {
      let downObj = { formType: this.formType }
      if (this.formType == 12) {
        this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-produce/produce')
      }
      downFile('/import/createImportTemplateXls', downObj)
        .then((data) => {
          if (!data) {
            this.$antdMessage.warning('模板下载失败')
            return
          }
          if (data.type != 'application/vnd.ms-excel') {
            this.$antdMessage.warning('模板下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), this.modelName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', this.modelName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
        .catch(() => this.$antdMessage.error('模板下载失败，请联系开发人员!', 1.5))
        .finally(() => {
          if (this.formType == 12) {
            this.$store.commit('SET_CURRENT_PREFIX', '')
          }
        })
    },
    handleChange(info) {
      const { fileLists } = this
      if (fileLists.length > 0) {
        let formData = new FormData()
        formData.append('file', fileLists[0])
        formData.append('formType', this.formType) //参数
        if (this.formType == 12) {
          this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-produce/produce')
        }
        fromDataPost('/import/importExcel', formData, 'post')
          .then((res) => {
            if (res.success) {
              if (this.formType == 10 || this.formType == 11) {
                this.$emit('getImportData', res.result)
              }
              this.close()
              this.$antdMessage.success(res.message)
            } else {
              this.$antdMessage.error(res.message)
            }
          })
          .catch((e) => {
            this.$antdMessage.error(res.message)
          })
          .finally(() => {
            if (this.formType == 12) {
              this.$store.commit('SET_CURRENT_PREFIX', '')
            }
            this.$emit('updateParentData')
          })
      }
    },
    showImportModal() {
      this.visible = true
      this.fileList = []
      this.fileLists = []
    },
    close() {
      this.visible = false
      this.current = 1
      let obj = {
        pageNo: this.current,
        pageSize: this.pageSize
      }
      this.getData(obj)
      this.$emit('updateParentData')
    },
    handleCancel() {
      this.visible = false
    },
    /***导入任务涉及的方法**/
    // 下载导入异常模板
    downAbnormal(item) {
      let url = apiBaseUrlDownload + 'sys/common/static/' + item.errorFileUri
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', `${item.tableName ? item.tableName : '异常模板'}.xls`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
    },
    changOpen(type) {
      if (type == 'upwards') {
        this.isOpen = false
      } else {
        this.isOpen = true
      }
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      let obj = {
        pageNo: this.current,
        pageSize: this.pageSize
      }
      this.getData(obj)
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize
      this.current = 1
      let obj = {
        pageNo: this.current,
        pageSize: this.pageSize
      }
      this.getData(obj)
    }
  }
}
</script>
<style>
.ant-alert-message {
  color: #ff943e !important;
}
</style>
<style lang='less' scoped>
.alert {
  margin: 0px -24px;
  margin-bottom: 24px;
}

.import-salary {
  padding-left: 15px;
  position: relative;
  color: #888;
  font-size: 14px;

  .icon {
    position: absolute;
    left: -9px;
    background: #fff;
    height: 18px;
  }
}

.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}

div.fixedBox {
  position: fixed;
  top: 59px;
  bottom: 0;
  right: 0;
  z-index: 999;
  background: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.6);
  width: 410px;

  div.headerBox {
    .flex(space-between, center);
    box-sizing: border-box;
    padding: 0px 24px;
    height: 56px;
    border-bottom: 1px solid #eeeeee;

    div.headerLeft {
      font-size: 16px;
      color: #444444;
    }

    img.headerRight {
      width: 12px;
      height: 12px;
      cursor: pointer;
    }
  }

  div.containerBox {
    height: calc(100% - 56px - 66px);
    overflow: auto;
    background-color: #ffffff;

    div.itemBox {
      div.itemOne {
        box-sizing: border-box;
        padding: 15px 23px;

        div.itemTop {
          .flex(space-between, center);
          margin-bottom: 14px;

          div.itemTop_left {
            .flex(flex-start, center);

            img.leftImg_ing {
              width: 12px;
              height: 13px;
              margin-right: 9px;
            }

            img.leftImg_success {
              width: 14px;
              height: 14px;
              margin-right: 8px;
            }

            img.leftImg_fail {
              width: 14px;
              height: 14px;
              margin-right: 8px;
            }

            div.leftText_ing {
              font-size: 14px;
              color: #1e8df5;
            }

            div.leftText_success {
              font-size: 14px;
              color: #00b042;
            }

            div.leftText_fail {
              font-size: 14px;
              color: #ff4d4f;
              opacity: 0.85;
            }
          }

          div.itemTop_right {
            font-size: 14px;
            color: #1e8df5;
            cursor: pointer;
          }
        }

        div.btnBox {
          margin-bottom: 16px;
        }

        div.itemCenter {
          font-size: 14px;
          margin-bottom: 9px;

          span.centerLeft {
            color: #888888;
          }

          span.centerRight {
            color: #444444;
          }
        }

        div.itemBot {
          font-size: 14px;

          span.botLeft {
            color: #888888;
          }

          span.botRight {
            color: #444444;
          }
        }
      }

      div.itemTwo {
        height: 6px;
        background: #eeeeee;
      }
    }
  }

  div.footerBox {
    height: 66px;
    .flex(flex-start, center);
    box-sizing: border-box;
    padding: 0 17px;
    background: #ffffff;
    box-shadow: 5px 0px 10px 0px rgba(0, 0, 0, 0.15);
  }
}

/deep/ .ant-modal-content {
  /deep/ .ant-modal-header {
    padding: 16px 24px 0 24px;
    border-bottom: none;
  }

  .ant-modal-body {
    padding: 0 24px 24px 24px;
  }
}
</style>
